# -- coding: utf-8 --
"""
# Example: Miahx 框架时间同步消息的发布、订阅和消费联动示例

Version: 0.4.5,
Last updated: May 10, 2024

## Contributor(s)
* YAO Naiming <[naiming@iscas.ac.cn](mailto:naiming@iscas.ac.cn)>

## Change log
### v0.4.5.10
- 新功能：新增初始实现

Copyright (c) All contributors, ISCAS & ASIC. 2024.
All rights reserved. Licensed under Apache-2.0.
"""

import datetime
import multiprocessing
import os
import sys
import time

from loguru import logger
from miahx_support.dds.fastdds import *

log = logger.bind()


def _start_gnss_writer(kr, lock):
    participant = Participant()
    writer = GNSSWriter(participant)
    writer.wait_discovery()
    iid: int = 0
    _keep_running = True
    while _keep_running:
        time.sleep(1)
        iid = (iid + 1) % (10 ** 5)
        now = datetime.datetime.now()
        writer.write(iid=iid, year=now.year, month=now.month, day=now.day,
                     hour=now.hour, minute=now.minute, second=now.second,
                     ns=now.microsecond * 1000)
        with lock:
            _keep_running = (kr.value == 1)


def _start_gnss_reader(messenger, fd, kr, lock):
    participant = Participant()
    with GNSSReader(participant, messenger=messenger) as reader:
        sys.stdin = os.fdopen(fd)
        # time.sleep(5)
        input('Press any key to stop\n')
        with lock:
            kr.value = 0


def _start_worker(messenger, k, kr, lock):
    _keep_running = True
    while _keep_running:
        _cond, _data = messenger
        with _cond:
            _cond.wait()
            log.info(f'Proc-{k}: {_data}')
        with lock:
            _keep_running = (kr.value == 1)


if __name__ == '__main__':
    # GNSS 消息的发布、订阅、消费
    _kr = multiprocessing.Value('i', 1)
    _lock = multiprocessing.Lock()

    proc_writer = multiprocessing.Process(target=_start_gnss_writer, args=(_kr, _lock,))
    proc_writer.start()

    mgr = multiprocessing.Manager()
    cond = mgr.Condition()
    data = mgr.dict()
    proc_reader = multiprocessing.Process(target=_start_gnss_reader,
                                          args=((cond, data), sys.stdin.fileno(), _kr, _lock,))
    proc_reader.start()

    proc_workers = []
    for i in range(5):
        proc_worker = multiprocessing.Process(target=_start_worker, args=((cond, data), i, _kr, _lock,))
        proc_worker.start()
        proc_workers.append(proc_worker)

    proc_writer.join()
    proc_reader.join()
    for p in proc_workers:
        p.join()

    log.info('Finished')
